import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import { previewDataInterface } from '@/api/systemData/dataInterface'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default {
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      visible: false,

      dataForm: {
        amount: 0,
        brand: undefined,
        campusInfo: undefined,
        campusName: undefined,
        createTime: undefined,
        customerInfo: undefined,
        enCode: undefined,
        id: undefined,
        managerId: undefined,
        method: undefined,
        name: undefined,
        status: undefined,
        time: undefined,
        type: undefined,
        description: undefined
      },
      brandOptions: [],
      typeOptions: [{ fullName: '加盟', id: '1' }, { fullName: '续约', id: '2' }, { fullName: '代理', id: '3' }],
      statusOptions: [{ fullName: '全款', id: '1' }, { fullName: '定金', id: '2' }, { fullName: '保证金', id: '3' }, { fullName: '余款', id: '4' }],
      moneyCheck: {
        0: '零',
        1: '壹',
        2: '贰',
        3: '叁',
        4: '肆',
        5: '伍',
        6: '陆',
        7: '柒',
        8: '捌',
        9: '玖'
      },
      printContent: null,
      down: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    async exportToPDF() {
      try {
        this.down = true
        const element = document.getElementById('printMe') // 获取需要导出的DOM元素

        // 将DOM转换为canvas
        await html2canvas(element, {
          allowTaint: true,
          useCORS: true, // 如果有跨域图片资源需要加载，开启这个选项
          scale: 2, // 设置缩放比例以提高PDF质量
          dpi: 192
        }).then(canvas => {
          let contentWidth = canvas.width
          let contentHeight = canvas.height
          const pdf = new jsPDF('1', 'pt', [contentWidth, contentHeight])
          const imgData = canvas.toDataURL('image/png', 1.0)
          pdf.addImage(imgData, 'PNG', 0, 0, contentWidth, contentHeight)
          pdf.save(this.dataForm.enCode + '.pdf')
          this.down = false
        })
        // 将canvas内容绘制到PDF中
        /* let pdf = new jsPDF('1', 'pt', 'a4');
        console.log(pdf)
        pdf.addImage(canvas.toDataURL('image/jpeg'), 'JPEG', 10, 10, 180, 260); // 参数根据实际尺寸调整
        // 生成并下载PDF
        pdf.save('票据.pdf');*/
      } catch (error) {
        this.down = false
        console.error('Error fetching component:', error)
        return null
      }
    },
    printPDF() {
      this.printContent = this.$refs.printMe
      const option = {
        dpi: 192,
        scale: 2
      }
      this.$nextTick(() => {
        html2canvas(this.printContent, option).then(canvas => {
          let contentWidth = canvas.width
          let contentHeight = canvas.height
          const pdf = new jsPDF('1', 'pt', [contentWidth, contentHeight])
          const imgData = canvas.toDataURL('image/png', 1.0)
          pdf.addImage(imgData, 'PNG', 0, 0, contentWidth, contentHeight)
          pdf.save('票据.pdf')
        })
      })
    },
    /*
     * 小写转换
     * */
    getMoneyBig(num) {
      return this.moneyCheck[num]
    },
    getStringSub(str, bl, index) {
      /*let a = ''
      const integerRegex = /^-?\d+$/;
      for (let i = 0; i < str.length; i++) {
        let item = str.substr(i,1)
        if (integerRegex.test(item)) {
          a += this.getMoneyBig(item)
        }
        if (item === '.') {
          a += '点'
        }
      }
      return a*/
      if (str) {
        str = str + ''
        const arr = str.split('.')
        if (bl > 0) {
          if (index >= arr[0].length) {
            return ''
          } else {
            return this.getMoneyBig(arr[0][arr[0].length - index - 1])
          }
        } else {
          if (arr.length > 1) {
            if (index >= arr[1].length) {
              return '零'
            } else {
              return this.getMoneyBig(arr[1][index])
            }
          } else {
            return '零'
          }
        }
      }
    },
    getUserList() {
      this.$store.dispatch('base/getUserList').then(res => {
        this.managerIdOptions = res.filter(o => o.enabledMark == 1 && o.positionId.indexOf('445842201948194053') > -1)
      })
    },
    goBack() {
      this.$emit('refresh')
    },
    init(id, row) {
      this.visible = true
      this.dataForm = row || undefined
      this.$nextTick(() => {})
    },
    onPrint() {
      let that = this
      const tabStyle = `
      <style>
        .body-print{
          font-family: 楷体;
          margin-bottom: 50px;
          padding: 20px 50px;
          font-size: 14px;
          color: #454545;
        }
        .print{
          font-family: 楷体;
          position: relative;
        }
        table {
          position: relative;
          //width: 1058px;
          background-image: url("./img/background.png");
          background-repeat: no-repeat;
          background-size: 50%;
          background-position: center;
          font-size: 14px;
          color: #454545;
          font-family: 楷体;
        }
        table, th, td {
          border: 1px solid  #b7b6b6;
          border-collapse: collapse;
        }
        th,td{
          min-width: 61px;
          height: 61px;
        }
        .cell-width-1{
          width: 61px;
        }
        .cell-width-4{
          width: calc(4 * 61px);
        }
        .cell-width-5{
          width: calc(5 * 61px);
        }
        .cell-width-7{
          width: calc(7 * 61px);
        }
        .cell-width-8{
          width: calc(8 * 61px);
        }
        .cell-width-12{
          width: calc(12 * 61px);
        }
        .row-height-1{
          height: 61px;
        }
        .row-height-3{
          height: calc(1 * 61px);
        }
        .flex-centent div{
          display: flex;
          flex-direction: column;
          align-items: center;

        }
        .flex-centent span{
          display: block;
        }
        .flex-pandding-25{
          padding-left: 25px;
        }
        .flex .details{
          display: flex;
          justify-content: space-between;
        }
        .flex .details div:nth-child(2){
          margin-right: 10px;
        }
        .flex-letter .letter{
          display: flex;
          justify-content: center;
        }
        .flex-letter .letter span:nth-child(1){
          width: 122px;
          text-align-last: justify;
        }
        .header img{
          width: 85px;
          height: 85px;
        }
        .header{
          display: flex;
          justify-content: space-between;
        }
        .header-centent{
          position: relative;
          font-size: 25px;
          height: 50px;
          font-family: 楷体;
          color: #454545;
          /*padding-top: 8px;*/
        }
        .header-last {
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
          margin-bottom: 5px;
          color: #454545; font-size: 14px
        }
        .header-centent::after {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          height: 2px; /* 横线的厚度 */
          background-image: linear-gradient( #000, transparent);
          width: 100%;
          /*transform: scaleY(0.5); !* 使横线看起来更细 *!*/
        }
        .header-centent::before {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          bottom: -2px;
          height: 2px; /* 横线的厚度 */
          background-image: linear-gradient( transparent, #000);
          width: 100%;
        }
</style>`
      this.getBase64(require('./img/background.png'), bg => {
        this.getBase64(require('./img/code.jpg'), list => {
          this.getBase64(require('./img/yz.png'), code => {
            var imgs = document.getElementsByClassName('imgBg')[0]
            var codeImg = document.getElementsByClassName('yz')[0]
            var tableBg = document.getElementsByClassName('print-table-bg')[0]
            imgs.setAttribute('src', list)
            imgs.setAttribute('style', 'width: 85px; height: 85px')

            codeImg.setAttribute('src', code)
            codeImg.setAttribute('style', 'width: 225px;\n' + '        position: absolute;\n' + '        right: 0;\n' + '        bottom: 53px;')

            tableBg.setAttribute('src', bg)
            tableBg.setAttribute('style', 'width: 50%; z-index: 100')

            // var myTitle=document.getElementsByClassName('header-centent')[0];
            // var beforeStyle=window.getComputedStyle(myTitle,':before');
            // var afterStyle=window.getComputedStyle(myTitle,':after');
            // beforeStyle.className += ' example-before'
            // beforeStyle.setAttribute('style', ' content: \'\';\n          position: absolute;\n          left: 0;\n          right: 0;\n          bottom: -2px;\n          height: 2px; /* 横线的厚度 */\n          background-image: linear-gradient( transparent, #000);\n          width: 100%;')
            // afterStyle.setAttribute('style', ' content: \'\';\n          position: absolute;\n          left: 0;\n          right: 0;\n          bottom: 0;\n          height: 2px; /* 横线的厚度 */\n          background-image: linear-gradient( #000, transparent);\n          width: 100%;')

            this.$nextTick(() => {
              const printForm = that.$refs.printMe.innerHTML
              const printStr = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head>"
              const printPart1 = printStr + tabStyle + '</body></html>'
              const printPart = printPart1 + printForm
              const newTab = window.open('_blank')
              newTab.document.body.innerHTML = printPart
              try {
                print.portrait = false
              } catch (e) {}
              newTab.print()
              newTab.close()
            })
          })
        })
      })
    },
    getBase64(url, callback) {
      const Img = new Image()
      let dataURL = ''
      Img.src = url + '?v=' + Math.random()
      Img.setAttribute('crossOrigin', 'Anonymous') // 解决控制台跨域报错的问题（没用就跟后台沟通添加跨域）
      Img.onload = function() {
        // 要先确保图片完整获取到，这是个异步事件
        const canvas = document.createElement('canvas') // 创建canvas元素
        const width = Img.width // 确保canvas的尺寸和图片一样
        const height = Img.height
        canvas.width = width
        canvas.height = height
        canvas.getContext('2d').drawImage(Img, 0, 0, width, height) // 将图片绘制到canvas中
        dataURL = canvas.toDataURL('image/' + url) // 转换图片为dataURL
        callback(dataURL)
      }
    }
  }
}
